﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using blackhouse.JavaScript.JQuery;

namespace blackhouse.Web.Controls.Validators {
    public class DefineValidator {

        private WebControl control;
        private string rule;

        public DefineValidator(WebControl controlToDefineValidator) {
            this.control = controlToDefineValidator;
        }

        public DefineValidator(WebControl controlToDefineValidator, string rule) {
            this.control = controlToDefineValidator;
            this.rule = rule;
        }

        public void AddValidator() {
            this.AddValidator(this.rule);
        }

        public void AddValidator(string rule) {
            if (string.IsNullOrEmpty(this.control.Attributes["data-validation-engine"]))
                this.control.Attributes.Add("data-validation-engine", "validate[" + rule + "]");
            else
                this.UpdateAttribute(rule);
        }

        public static void LoadScript() {
            JQueryLibraries jql = new JQueryLibraries();
            jql.IncludeJQueryValidationEngine(CultureInfo.CurrentCulture);
            jql.IncludeFileBasedOnJQuery("blackhouse.Web.Controls.Validators.validators.js,blackhouse.Web.Controls");
        }

        private void UpdateAttribute(string rule) {
            string attr = this.control.Attributes["data-validation-engine"];
            attr = attr.Substring(0, attr.Length - 1) + "," + rule + "]";
            this.control.Attributes["data-validation-engine"] = attr;
        }

        public void AddMessage(string message) {
            this.AddMessage(this.rule, message);
        }

        public void AddMessage(string rule, string message) {
            string key = "data-errormessage-" + rule;
            message = message.ReplaceEx("\"", "\\\"");
            if (string.IsNullOrEmpty(this.control.Attributes[key]))
                this.control.Attributes.Add(key, message);
            else
                this.control.Attributes[key] = message;
        }

    }
}